package cn.icare.cms;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * @Classname XmlUtil
 * @Description TODO XML操作辅助类
 * @Date 2020/3/20 17:51
 * @Created by Administrator
 */
public class XmlUtil {

    private  static final String ENCODING="UTF-8";
    protected static Logger logger = LoggerFactory.getLogger(XmlUtil.class);

    /**
     * 对象序列化为xml字符串
     * @param msg
     * @return
     */
    public static String serializer(Object msg) {
        String result = null;
        try {
            //创建输出流
            StringWriter sw = new StringWriter();
            //利用jdk中自带的转换类实现
            JAXBContext context = JAXBContext.newInstance(msg.getClass());
            Marshaller marshaller = context.createMarshaller();
            //格式化xml输出的格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            //去掉生成xml的默认报文头
            marshaller.setProperty(Marshaller.JAXB_ENCODING, ENCODING);
            // 将对象转换成输出流形式的xml
            marshaller.marshal(msg, sw);
            result = sw.toString();
        } catch (Exception ex) {
            logger.error(String.format("serializer error: %s", ex.getMessage()));
        }
        return result;
    }

    /**
     * xml字符串反序列化为对象
     * @param msg
     * @param msgType
     * @return
     */
    public static Object deserialize(String msg, Class... msgType) {
        Object result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(msgType);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            StringReader sr = new StringReader(msg);
            result = unmarshaller.unmarshal(sr);
        } catch (Exception ex) {
            logger.error(String.format("deserialize error: %s", ex.getMessage()));
        }
        return result;
    }
}
